package com.tanhua.admin.service;

import cn.hutool.core.date.DateUtil;
import com.bilibili.model.db.Analysis;
import com.bilibili.model.vo.AnalysisSummaryVo;
import com.tanhua.admin.mapper.AnalysisMapper;
import com.tanhua.admin.mapper.LogMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;

/**
 * @author HuangRongFu
 * 2021/11/30 星期二11:19 上午
 */

@Service
public class AnalysisService {

    @Autowired
    private LogMapper logMapper;

    @Autowired
    private AnalysisMapper analysisMapper;

    /**
     * 数据统计
     */
    public void analysis() {

        Date date = new Date();

        //获取今天和昨天的日期字符串
        String today = DateUtil.today();
        String yesterday = DateUtil.yesterday().toDateStr();


        //统计新注册用户数
        Integer numRegistered = logMapper.countNumRegisteredToday(today);

        //活跃用户数
        Integer numActive = logMapper.countNumActiveByDate(today);

        //登录次数
        Integer numLogin = logMapper.countNumLoginByDate(today);

        //5. 次日留存用户数
        Integer numRetention1d = logMapper.countNumRetention1d(today, yesterday);

        //构建pojo
        Analysis pojo = new Analysis();
        pojo.setUpdated(date);
        pojo.setNumRegistered(numRegistered);
        pojo.setNumActive(numActive);
        pojo.setNumLogin(numLogin);
        pojo.setNumRetention1d(numRetention1d);

        //判断是否在数据库中存在
        Analysis analysisInDb = analysisMapper.findByRecordDate(today);

        //不存在新增
        if (analysisInDb == null) {

            pojo.setRecordDate(date);
            pojo.setUpdated(date);
            analysisMapper.insert(pojo);

        } else {

            //存在则更新
            pojo.setId(analysisInDb.getId());
            analysisMapper.updateById(pojo);
        }
    }

    /**
     * 首页统计
     */
    public AnalysisSummaryVo summary() {

        //今天 昨天 过去一周 过去一月
        String today = DateUtil.today();
        String yesterday = DateUtil.yesterday().toDateStr();
        String last7day = DateUtil.offsetDay(new Date(), -7).toDateStr();//偏移7天
        String last30day = DateUtil.offsetDay(new Date(), -30).toDateStr();//偏移30天

        //查询数据封装到vo
        AnalysisSummaryVo vo = new AnalysisSummaryVo();

        vo.setCumulativeUsers(analysisMapper.totalUser());
        vo.setActivePassWeek(logMapper.countAfterDate(last7day));
        vo.setActivePassMonth(logMapper.countAfterDate(last30day));

        //今日数据
        Analysis todayData = analysisMapper.findByRecordDate(today);

        vo.setNewUsersToday(todayData.getNumRegistered().longValue());
        vo.setLoginTimesToday(todayData.getNumLogin().longValue());
        vo.setActiveUsersToday(todayData.getNumActive().longValue());

        //昨日数据
        Analysis yesterdayData = analysisMapper.findByRecordDate(yesterday);

        //算环比
        vo.setNewUsersTodayRate(computeRate(todayData.getNumRegistered().longValue(),
                yesterdayData.getNumRegistered().longValue()));

        vo.setLoginTimesTodayRate(computeRate(todayData.getNumLogin().longValue(),
                yesterdayData.getNumLogin().longValue()));

        vo.setActiveUsersTodayRate(computeRate(todayData.getNumActive().longValue(),
                yesterdayData.getNumActive().longValue()));

        return vo;

    }

    private static BigDecimal computeRate(Long current, Long last) {
        BigDecimal result;
        if (last == 0) {
            // 当上一期计数为零时，此时环比增长为倍数增长
            result = new BigDecimal((current - last) * 100);
        } else {
            result = BigDecimal.valueOf((current - last) * 100).divide(BigDecimal.valueOf(last), 2, BigDecimal.ROUND_HALF_DOWN);
        }
        return result;
    }
}
